<?php
/**
 * Created by PhpStorm.
 * FileName: AppointmentModel.php
 * User: Administrator
 * Date: 2018/4/13
 * Time: 15:25
 */

namespace Admin\Model;

use Think\Db;
use Think\Model\RelationModel;

class BespeakModel extends RelationModel {

    protected $tableName = 'bespeak';

    protected $_link = array(
        'user' => array(
            'mapping_type' => self::BELONGS_TO,
            'class_name' => 'Admin/User',
            'foreign_key' => 'user_id',
            'mapping_key'  => 'id'
        ),
        'member' => array(
            'mapping_type' => self::BELONGS_TO,
            'class_name' => 'Admin/User',
            'foreign_key' => 'member_id',
            'mapping_key'  => 'id'
        ),
        'org' => array(
            'mapping_type' => self::BELONGS_TO,
            'class_name' => 'Organization',
            'foreign_key' => 'org_id',
            'mapping_key'  => 'id'
        ),
    );

    public function getList($where=array(),$pageSize=15,$order='order_time desc') {
        $data = array();
        $count = $this->where($where)->count();
        $pageInfo = getPage($count,$pageSize);
        $dataList = $this->relation(true)->where($where)->order($order)->limit($pageInfo->firstRow,$pageInfo->listRows)->select();
        $data['list'] = $this->formatStatus($dataList);
        $data['pageInfo'] = $pageInfo;
        $data['nowPage'] = $pageInfo->nowPage ? $pageInfo->nowPage : 0;
        $data['page'] = $pageInfo->show();
        return $data;
    }

    public function apiList($where=array(),$curPage=1,$pageSize=15,$order='order_time desc') {
        $data = array();
        $count = $this->where($where)->count();
        $totalPage = ceil($count/$pageSize);
        $curPage = ($curPage > 0) ? $curPage : 1;
        $firstRow = ($curPage-1)*$pageSize;
        $dataList = $this->relation(true)->where($where)->order($order)->limit($firstRow,$pageSize)->select();
        $data['list'] = $this->formatStatus($dataList);
        $data['count'] = $count;
        $data['curPage'] = $curPage;
        $data['totalPage'] = $totalPage;
        return $data;
    }

    public function add($data) {
        $data['order_time'] = strtotime($data['order_time']);
        $data['create_time'] = time();
        return parent::add($data);
    }

    /**
     * 验证指定预约时段是否有效
     * @param $orgId 部门id
     * @param $userId 服务人员id
     * @param $orderTime 预约日期
     * @param $timeRange 预约时间段
     * @return bool true 有效 | false 无效
     */
    public function isValid($orgId,$userId,$orderTime,$timeRange) {
        $where = array(
            'org_id' => $orgId,
            'user_id' => $userId,
            'order_time' => strtotime($orderTime),
            'time_range' => $timeRange,
            'status' => 1
        );
        //已预约人数
        $count = $this->where($where)->count();
        //预约总人数
        $appWhere = array(
            'org_id' => $orgId,
            'user_id' => $userId,
            'order_time' => strtotime($orderTime)
        );
        $total = M('appointment')->where($appWhere)->getField('nums');
        $total = $total ? $total : 0;
        return $count<$total ? true : false;
    }

    /**
     * 获取已经被预约过的时间段
     * @param $orgId
     * @param $orderTime
     * @return array
     */
    public function getBespeaks($orgId,$orderTime) {
        $where = array(
            'org_id' => $orgId,
            'order_time' => strtotime($orderTime),
            'status' => 1
        );
        $bespeaks = $this->where($where)->field('user_id,time_range')->select();
        $reservedTimeRange = array();
        foreach ($bespeaks as $bespeak) {
            $reservedTimeRange[$bespeak['user_id']][] = $bespeak['time_range'];
        }
        return $reservedTimeRange;
    }

    /**
     * 获取每个部门指定日期已被预约的人数
     * @param $orgId
     * @param $orderTime
     * @return mixed
     */
    public function getReservedNums($orgId,$orderTime,$timeRange) {
        $where = array(
            'org_id' => $orgId,
            'order_time' => strtotime($orderTime),
            'time_range' => $timeRange,
            'status' => 1
        );
        $total = $this->where($where)->count();
        return $total;
    }

    /**
     * 统计每个预约时间段内的预约人数
     * @return mixed
     */
    public function getReservedNumsByUser($curTime) {
        $where = array(
            'status' => 1,
            'FROM_UNIXTIME(order_time,\'%Y-%m-%d\')' => $curTime
        );
        $groupField = 'user_id,org_id,time_range';
        $result = $this->field('count(1) as surplus,'.$groupField)->where($where)->group($groupField)->select();
        return $result;
    }

    private function formatStatus($rows) {
        foreach ($rows as $key => $row) {
            if ($row['status'] == 0) {
                //已取消
                continue;
            }
            $orderDate = date('Y-m-d H:i:s',$row['order_time']);
            $timeRange = $row['time_range'];
            $rangeStart = sprintf('%s:00',substr($timeRange,0,5));
            $rangeEnd = sprintf('%s:00',substr($timeRange,8));
            $orderStart = strtotime(str_replace('00:00:00',$rangeStart,$orderDate));
            $orderEnd = strtotime(str_replace('00:00:00',$rangeEnd,$orderDate));

            if ($orderEnd < time()) {
                //已结束
                $rows[$key]['status'] = 2;
            } elseif ($orderStart > time()) {
                //未开始
                $rows[$key]['status'] = 1;
            } else {
                //进行中
                $rows[$key]['status'] = 3;
            }
        }
        return $rows;
    }

}